﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observer_C_Shaper_
{   
    public class WeatherData : IObservable<Data> {
        private List<IObserver<Data>> observers;

        public WeatherData() {
            this.observers = new List<IObserver<Data>>();
        }

        public IDisposable Subscribe(IObserver<Data> observer) {
           if(!observers.Contains(observer)) {
               observers.Add(observer);
           }
            return new Unsubscriber(observers, observer);
        }

        private class Unsubscriber : IDisposable {
            private List<IObserver<Data>> _observers;
            private IObserver<Data> _observer;

            public Unsubscriber(List<IObserver<Data>> observers, IObserver<Data> observer) {
                _observers = observers;
                _observer = observer;
            }

            public void Dispose() {
               if(_observer != null && _observers.Contains(_observer)) {
                   _observers.Remove(_observer);
               }
            }
        }

        public void UpdateData(Nullable<Data> data) {
            foreach (var observer in observers) {
                if(!data.HasValue)
                    observer.OnError(new Exception());
                else {
                    observer.OnNext(data.Value);
                }
            }
        }

        public void EndTransmission() {
            foreach (var observer in observers.ToArray()) {
               if(observers.Contains(observer))
                   observer.OnCompleted();
            }
            observers.Clear();
        }
    }
}
